package dao

import (
	"goblog/models"
	"github.com/astaxie/beego/orm"
	"fmt"
)

type CategoryDao struct {
	Dao orm.Ormer
}

type CategoryTerm struct {
	models.Term
	Pid    int    `json:"pid"`
	Level  int    `json:"level"`
}

func (this *CategoryDao) Get(id int) models.Category {
	if this.Dao == nil {
		this.Dao = orm.NewOrm()
	}
	var category models.Category
	this.Dao.Raw(" SELECT id, pid, name, parent, level, updated, created from article_catalog where id=?", id).QueryRow(&category)
	return category
}

func (this *CategoryDao) FindFirst() []models.Category {
	if this.Dao == nil {
		this.Dao = orm.NewOrm()
	}
	var categories []models.Category
	this.Dao.Raw(" SELECT id, pid, name, parent, level, updated, created from article_catalog where level=?", 1).QueryRows(&categories)
	return categories
}

func (this *CategoryDao) FindChild(id int) []models.Category {
	if this.Dao == nil {
		this.Dao = orm.NewOrm()
	}
	var categories []models.Category
	this.Dao.Raw("select id, pid, name, parent, level, updated, created from article_catalog where pid=?", id).QueryRows(&categories)
	return categories
}

func (this *CategoryDao) Find(term *CategoryTerm) {
	if this.Dao == nil {
		this.Dao = orm.NewOrm()
	}
	var args []interface{}
	var categories []models.Category
	sql := "select id, pid, name, parent, level, updated, created from " +
		"article_catalog where 1=1"
	if term.Pid > 0 {
		sql += " and pid=?"
		args = append(args, term.Pid)
	}

	if term.Level > 0 {
		sql += " and level=?"
		args = append(args, term.Level)
	}

	id, err := Paging(sql, args, &term.Term, this.Dao).QueryRows(&categories)
	if err != nil {
		panic(err)
		fmt.Println(id)
	}
	term.Data = categories
}
